package ru.smc.hogwarts.servlets.professors;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.classes.HashMd5;
import ru.smc.hogwarts.model.House;
import ru.smc.hogwarts.model.Person;
import ru.smc.hogwarts.model.Role;

public class ProfessorsAdd extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String error = "";
	private String firstName = null;
	private String lastName = null;
	private String status = null;
	private int house = 0;
	private String pInfo = null;
	private HttpSession session;
       
    public ProfessorsAdd() {
        super();
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("error", error);
		
		session = request.getSession(true);
    	session.setAttribute("servletName", getServletName());
    	
    	EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
		
		List<House> houses = em.createQuery("select h from House h").getResultList();
		request.setAttribute("houses", houses);
		
		em.close();
		
		if (error == "") {
			firstName = null;
			lastName = null;
			status = null;
			house = 0;
			pInfo = null;	
		}
		
		request.setAttribute("firstName", firstName);
		request.setAttribute("lastName", lastName);
		request.setAttribute("status", status);
		request.setAttribute("house", house);
		request.setAttribute("pInfo", pInfo);
		
		error = "";
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/pages/professors/professorAdd.jsp");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		error = "";
		
		try {			
			firstName = request.getParameter("firstName");
			if (firstName == "") 
				error += "<span>П</span>оле \"Имя\" не должно быть пустым.<br>";
						
			lastName = request.getParameter("lastName");
			if (lastName == "") 
				error += "<span>П</span>оле \"Фамилия\" не должно быть пустым.<br>";
			
			status = request.getParameter("status");
			if (status == "") 
				error += "<span>П</span>оле \"Статус\" не должно быть пустым.<br>";
			
			if (request.getParameter("house") == "") {
				error += "<span>П</span>оле \"Факультет\" не должно быть пустым.<br>";
			} else {
				house = Integer.parseInt(request.getParameter("house"));
			}
			
			pInfo = request.getParameter("pInfo");
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		if (error == "") { 
			this.addProfessor(firstName, lastName, status, house, pInfo);
			response.sendRedirect(request.getContextPath() + "/professors");
		} else if (error != "") {
			response.sendRedirect(request.getContextPath() + "/professors/add");
		}
	}
	
	private void addProfessor(String firstName, String lastName, 
			String status, int house, String pInfo) {
		EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		
		Role role = em.find(Role.class, 5);
		House _house = em.find(House.class, house);
		
		Person person = new Person();
		
		person.setFirstName(firstName);
		person.setLastName(lastName);
		person.setStatus(status);
		person.setHouse(_house);
		person.setpInfo(pInfo);
		person.setPassword("");
		person.setLogin("");
		person.setRole(role);
		
		em.persist(person);
		em.getTransaction().commit();
		em.getTransaction().begin();
		
		String login = "h"+_house.getId()+"p"+person.getId();
		String hash_password = null;
		
		HashMd5 auth = new HashMd5();
		try {
			hash_password = auth.getHash(login);
		} catch (NoSuchAlgorithmException e) {}
		
		person.setPassword(hash_password);
		person.setLogin(login);
		
		em.persist(person);
		em.getTransaction().commit();
		
		em.close();
	}

}
